<!--
* @author: XJC
* @date: 2023-11-27 10:10
* @description：物料信息-用户端
* @update: 2023-11-27 10:10
-->
<template>
  <div class="container">
    <div class="app-container">
      <div class="inventory-top form-top">
        <el-form ref="materialForm" :model="materialForm" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="物料名称">
                <el-select
                  style="width: 100%"
                  filterable
                  v-model="materialForm.name"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in materialName"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号">
                <el-select
                  style="width: 100%"
                  filterable
                  v-model="materialForm.model"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in standardsList"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键字">
                <el-input
                  style="width: 100%"
                  v-model.trim="materialForm.keyword"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24" style="text-align: center">
              <el-button class="chamfer-98" type="primary" @click="searchBtn"
                >查询</el-button
              >
              <el-button
                style="margin-left: 20px"
                class="chamfer-98"
                plain
                @click="resetBtn"
                >重置</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="inventory-bot table-normal">
        <div class="btnBox" style="text-align: right">
          <el-button
            type="primary"
            class="chamfer-98"
            @click="manualRequisitionBtn"
          >
            <span class="btn-middle">
              <span>领用</span>
              <img class="btn-icon" src="~@/assets/material_img/addBtn.png" />
            </span>
          </el-button>
          <el-button type="primary" class="chamfer-98" @click="manualReturnBtn">
            <span class="btn-middle">
              <span>归还</span>
              <img class="btn-icon" src="~@/assets/material_img/delBtn.png" />
            </span>
          </el-button>
        </div>
        <el-table
          v-loading="loading"
          element-loading-background="rgba(0, 0, 0, 0.6)"
          ref="refTable"
          :data="materialTable"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          fit
          style="width: 100%"
          header-row-class-name="tableHeader"
          header-cell-class-name="tableTrHeader"
          row-class-name="tableRow"
          cell-class-name="tableCell"
          @row-click="clickTable"
          @selection-change="handleSelectionChange"
          @expand-change="expandSelect"
        >
          <el-table-column
            align="center"
            type="selection"
            width="160"
            label-class-name="DisabledSelection"
          />
          <el-table-column
            type="index"
            label="序号"
            width="160"
            align="center"
          />
          <el-table-column
            prop="name"
            label="物料名称"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column prop="model" label="规格型号" align="center" />
          <el-table-column prop="totalCount" label="在库总数" align="center">
            <template v-slot="{ row }">
              <span :class="row.totalCount == 0 ? 'colorRed' : ''">{{
                row.totalCount
              }}</span>
            </template>
          </el-table-column>
          <el-table-column type="expand" width="1">
            <template v-slot="{ row }">
              <el-table
                :data="row.secondTable"
                border
                header-row-class-name="tableHeaderSnd"
                header-cell-class-name="tableTrHeaderSnd"
                row-class-name="tableRowSnd"
                cell-class-name="tableCellSnd"
                style="width: 95%; margin: 0 auto"
              >
                <el-table-column
                  prop="shelvesName"
                  label="货架名称"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="positionName"
                  label="库位号"
                  align="center"
                >
                  <template v-slot="{ row }">
                    {{row.layerSort}} - {{row.positionName}}
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="在库数量" align="center">
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <paging-component
          :total="total"
          :page-size="materialForm.currentSize"
          :current-page="materialForm.currentPage"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 确认领用物料弹窗 -->
    <collection-dialog
      :isType="type"
      :showDialog.sync="showDialog"
      :title="title"
      :useContent="useContent"
      :materials="multipleSelection"
      @requisitionCompleted="requisitionCompleted"
      @revokeFn="revokeFn"
    />
      <!-- :isCollect="isCollect" -->
    <!-- 实时出入库弹窗 -->
    <realTimeStorage
      :model="3"
      :task-name="taskName || '默认任务'"
      :nick-name="nickName"
      :showDialog.sync="showTimeDialog"
      :inOutList="inOutList"
      :goodsList="goodsList"
      :isType="type"
      @operationCompleted="operationCompleted"
      ref="realTimeStorage"
    />
  </div>
</template>

<script>
import { getGoodsPositionBindApi } from '@/api/inventoryManage'
import RealTimeStorage from '@/components/realTimeStorage/index.vue'
import {
  getMaterialList,
  getMaterialNameList,
  getMaterialModelList
} from '@/api/materialManage'
import pagingComponent from '@/components/PagingComponent/index.vue'
import CollectionDialog from './components/collectionDialog.vue'
export default {
  components: { pagingComponent, CollectionDialog, RealTimeStorage },
  data() {
    return {
      // 物料信息表单
      materialForm: {
        name: '', // 物料名称
        model: '', // 规格型号
        keyword: '', // 关键字
        currentPage: 1, // 页码
        currentSize: 20 // 页尺寸
      },
      total: 0, // 库存余量总数
      // 物料名称
      materialName: [],
      // 规格型号
      standardsList: [],
      // 库存余量预警记录列表
      materialTable: [],
      expands: [], // 展开行,数组形式
      multipleSelection: [], // 表格选中数据
      showDialog: false, // 领用/归还物料弹窗
      title: '确认领用物料', // 领用/归还物料标题
      useContent: '领用', // 领用/归还物料内容
      loading: false, // 加载动画
      inOutList: [], // webSocket返回的数据
      showTimeDialog: false, // 控制实时出入库弹窗
      // isCollect: false, // 是否出库
      type: 0, // 出入库状态
      taskName: '', // 任务名称
      goodsList: [], // 物料信息出入库列表
      nickName: '' // 操作人
    }
  },
  created() {
    this.renderList()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素，一般在此执行：开启定时器，发送网络请求，订阅消息，绑定自定义事件等初始化操作。）
  mounted() {
    this.$eventBus.$on('webSocketMsgPage', this.operateMessage)
  },

  // 生命周期-页面销毁前（在销毁前，实例中所有的data、methods、computed、指令等，都处于可用状态在此阶段，一般进行：关闭定时器、取消订阅消息解绑自定义事件等收尾工作。）
  beforeDestroy() {
    this.$eventBus.$off('webSocketMsgPage', this.operateMessage)
  },
  methods: {
    // 获取列表
    async renderList() {
      this.loading = true
      const { result } = await getMaterialList(this.materialForm)
      this.total = Number(result.totalCount)
      this.materialTable = result.currentData
      // 更新下拉菜单数据
      let { result: list1 } = await getMaterialNameList()
      this.materialName = list1
      let { result: list2 } = await getMaterialModelList()
      this.standardsList = list2
      this.loading = false
    },
    // 查询
    searchBtn() {
      this.materialForm.currentPage = 1
      this.renderList()
    },
    // 重置
    resetBtn() {
      this.materialForm = {
        name: '', // 物料名称
        model: '', // 规格型号
        keyword: '', // 关键字
        currentPage: 1, // 页码
        currentSize: 20 // 页尺寸
      }
      this.renderList()
    },
    // pageSize改变时会触发(每页数据条数)
    handleSizeChange(val) {
      this.materialForm.currentSize = val
      this.renderList()
    },
    // currentPage改变时会触发(当前页码数)
    handleCurrentChange(val) {
      this.materialForm.currentPage = val
      this.renderList()
    },
    // 手动归还按钮
    manualReturnBtn() {
      this.useContent = '归还'
      this.type = 2
      // 校验：数据应大于一条
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择要归还的物料!'
        })
        return
      }
      this.title = '确认归还物料'
      this.multipleSelection.forEach((item) => {
        this.$set(item, 'goodsId', item.id)
        this.$set(item, 'goodsImage', item.imageBase64)
        this.$set(item, 'goodsName', item.name)
        this.$set(item, 'goodsModel', item.model)
        this.$set(item, 'planCount', 0)
        this.$set(item, 'realCount', 0)
        this.$set(item, 'isEdit', false)
        // 出入库类型 0-正常 1-出库 2-入库
        this.$set(item, 'type', 2)
      })
      this.showDialog = true
    },
    // 手动领用按钮
    manualRequisitionBtn() {
      this.useContent = '领用'
      this.type = 1
      // 校验：数据应大于一条
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择要领用的物料!'
        })
        return
      }
      if (this.multipleSelection.some((ele) => ele.totalCount == 0)) {
        this.$message({
          type: 'error',
          message: '领用物料中存在在库数量为0的物料!'
        })
        return
      }
      this.title = '确认领用物料'
      this.multipleSelection.forEach((item) => {
        this.$set(item, 'goodsId', item.id)
        this.$set(item, 'goodsImage', item.imageBase64)
        this.$set(item, 'goodsName', item.name)
        this.$set(item, 'goodsModel', item.model)
        this.$set(item, 'planCount', 0)
        this.$set(item, 'realCount', 0)
        this.$set(item, 'isEdit', false)
        // 出入库类型 0-正常 1-出库 2-入库
        this.$set(item, 'type', 1)
      })
      this.showDialog = true
    },

    // 接收websocket消息
    operateMessage(data) {
      if (data.type === 'inout' && data.message === 'closed') {
        this.inOutList = []
      }  else  {
        // if (data.type === 'inout' && data.message !== 'closed')
        if (this.showTimeDialog){
          this.inOutList = JSON.parse(data.message)
        }
      }
    },
    // 实时出入库弹窗确认按钮
    operationCompleted() {
      this.showTimeDialog = false
      this.showDialog = false
      this.searchBtn()
    },
    // 获取勾选数据表格
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击表格行
    async clickTable(row, index, e) {
      this.$refs.refTable.toggleRowExpansion(row)
      if (!row.secondTable) {
        let i = this.materialTable.findIndex((ele) => ele.id == row.id)
        let { result } = await getGoodsPositionBindApi({ goodsId: row.id })
        this.$set(this.materialTable[i], 'secondTable', result)
      }
    },
    // 撤销
    revokeFn(id) {
      let index = this.multipleSelection.findIndex((ele) => ele.id == id)
      this.multipleSelection.splice(index, 1)
    },
    requisitionCompleted(list, taskName,nickName) {
      console.log(list,"确认")
      this.goodsList = list
      this.taskName = taskName
      this.nickName = nickName || ''
      // 将vuex中的isRealTimeOpen设置为true
      this.$store.commit('settings/CHANGE_SETTING', {
        key: 'isRealTimeOpen',
        value: true
      })
      // 打开实时出入库弹窗
      this.showTimeDialog = true
    },

    // 每行的唯一key值 用其id表示
    getRowKeys(row) {
      return row.id
    },
    rowKey(row) {
      return row.id
    },
    // 展开行同时折叠其他行
    expandSelect(row, expandedRows) {
      let that = this
      if (expandedRows.length) {
        that.expands = []
        if (row) {
          that.expands.push(row.id)
        }
      } else {
        that.expands = []
      }
    }
  }
}
</script>

<style lang="scss">
@import '~@/styles/_handle.scss';

.is-active {
  .el-radio-button__inner {
    @include background('radio_bg_active');
  }
}
.el-radio-button__inner {
  @include background('radio_bg');
}
.contentBox {
  @include background('content_bg_color');
}
.inventory-bot {
  .el-table {
    // 表格全选框去除空框
    .DisabledSelection .cell .el-checkbox__inner {
      display: none;
      position: relative;
    }
    .el-table__body-wrapper{
      height: calc(100% - 48px);
      overflow-y: auto;
    }
    .el-table__body-wrapper::-webkit-scrollbar{
      width: 6px;
      height: 8px;
    }
    // 二级
    .tableTrHeaderSnd {
      font-weight: normal;
      border: 1px solid;
      @include border_color('second_table_border_color');
      @include background('second_table_head_bg_color');
    }
    // 二级
    .tableCellSnd {
      color: #ffffff;
      font-size: 18px;
      border: 1px solid;
      @include border_color('second_table_border_color');
      @include background('second_table_row_bg_color');
    }
    .expanded {
      @include background('second_table_expanded_bg_color');
    }
  }
}
.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  @include background('table_hover_color');
}
</style>
<style scoped lang="scss">
@import '~@/styles/_handle.scss';
.container {
  height: calc(100% - 80px);
  padding: 0 30px;
}
.app-container {
  width: 100%;
  height: 100%;
  padding: 25px 20px;
  margin-top: 24px;
  border-radius: 10px;
  border: 1px solid;
  @include border_image('container_border');
  @include background('content_bg_color');
}
.inventory-top {
  @include background('table_head_bgcolor');
}
::v-deep .app-container {
  .inventory-top {
    padding: 20px;
    width: 100%;
    height: 141px;
    border-radius: 10px;
    .el-form-item {
      margin-bottom: 16px;
    }
    .chamfer-98 {
      font-size: 18px;
    }
  }
  .inventory-bot {
    height: calc(100% - 141px);
    padding: 20px 10px;
    .btnBox {
      height: 44px;
      .chamfer-98 {
        font-size: 18px;
        text-align: center;
        .btn-middle {
          display: flex;
          align-items: center;
          .btn-icon {
            margin-left: 4px;
            width: 16px;
            height: 16px;
          }
        }
      }
    }
    .el-table {
      height: calc(100% - 100px);
      tr {
        background: transparent;
      }
      margin-top: 14px;
      background: transparent;
      border: none;
      .tableTrHeader {
        border: none;
      }
      // 二级
      .tableHeaderSnd {
        color: #ffffff;
        font-size: 18px;
      }
    }
    // 隐藏折叠小箭头
    .el-table__expand-icon {
      color: transparent;
    }
    .el-table::before {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0;
    }
    .el-table--border::after, .el-table--group::after {
      top: 0;
      right: 0;
      width: 0;
      height: 100%;
    }
  }
}
// ::v-deep .el-table td.el-table__cell,
// .el-table th.el-table__cell.is-leaf {
//   border-bottom: none;
// }

// 二级表格行背景色透明
::v-deep .el-table__cell.el-table__expanded-cell {
  background: transparent;
}
// 暂无数据时展示样式
::v-deep .el-table__empty-block {
  min-height: 240px;
  font-size: 20px;
}
// 取消表格底部横线
// ::v-deep .el-table--border::after,
// .el-table--group::after,
// .el-table::before {
//   content: none;
// }
.colorRed {
  color: #ff1f06;
  font-weight: 700;
}
</style>
